package com.jinzhi.jzapi.common.async;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@Configuration
@ComponentScan
@EnableAsync
// 线程配置类
public class AsyncTaskConfig implements AsyncConfigurer {
    // ThredPoolTaskExcutor的处理流程
    // 当池子大小小于corePoolSize，就新建线程，并处理请求
    // 当池子大小等于corePoolSize，把请求放入workQueue中，池子里的空闲线程就去workQueue中取任务并处理
    // 当workQueue放不下任务时，就新建线程入池，并处理请求，如果池子大小撑到了maximumPoolSize，就用RejectedExecutionHandler来做拒绝处理
    // 当池子的线程数大于corePoolSize时，多余的线程会等待keepAliveTime长时间，如果无请求可处理就自行销毁
//    AsyncTaskConfig asyncTaskConfig=new AsyncTaskConfig();
//    Executor executorService=asyncTaskConfig.getAsyncExecutor();
//
    private static ExecutorService executor = new ThreadPoolExecutor(10, 10,
            60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue(10));



    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);// 最小线程数
        taskExecutor.setMaxPoolSize(60);// 最大线程数
        taskExecutor.setQueueCapacity(25);// 等待队列

        taskExecutor.initialize();

        return taskExecutor;
    }
    @Async
    // 表明是异步方法
    // 无返回值
    public void executeAsyncTask(Integer i) throws InterruptedException {
        System.out.println("input is " + i);
       // Thread.sleep(2000 * random.nextInt(i));
        System.out.println("执行异步任务：" + i);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }

    // 测试无返回结果
    private static void testVoid() throws InterruptedException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AsyncTaskConfig.class);
        AsyncTaskConfig asyncTaskService = context.getBean(AsyncTaskConfig.class);

        long s = System.currentTimeMillis();
        // 创建了20个线程
        for (int i = 1; i <= 20; i++) {
            asyncTaskService.executeAsyncTask(i);
        }
        long end = System.currentTimeMillis();
        long l = end - s;
        System.out.println("jiesushijian:"+l+"");
        context.close();
    }


   // private ExecutorService executor = Executors.newFixedThreadPool(10, "SynchronizeHistoricalDataController");  //newFixedThreadPool 创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。


}
